<?php

/**
 * Created by PhpStorm.
 * User: wangkaihui
 * Date: 2017/7/4
 * Time: 13:42
 */
class My_Session_Db
{
    protected static $sid = null;
    protected $config=[];
    protected $preKey = null;

    public function __construct($key='')
    {
        $config = My::config()->getInit();
        $config = $config['session'];
        $this->config = $config;
        $this->preKey = $key;
    }

    public function start()
    {
        if(!$this->config) return ;

        $config = $this->config;

        $sid = null;

        $lifetime = $this->getLifeTime();

        $path = !isset($config['path']) ? '/' : $config['path'];
        $domain = !isset($config['domain']) ? '' : $config['domain'];
        $secure = !isset($config['secure']) ? false : $config['secure'];
        $httponly = !isset($config['httponly']) ? true : $config['httponly'];

        $sessionName = empty($config['name']) ? 'YSESSIONID' : $config['name'];

        $sid = $this->getSid();

        setcookie($sessionName, $sid, $lifetime, $path, $domain, $secure, $httponly);

        $this->set("yusns_heart", 1);
    }

    protected function getLifeTime()
    {
        $config = $this->config;
        if (isset($config['cache_expire'])) {
            $expire = $config['cache_expire'];
            $lifetime = time()+$expire;
        } else {
            $lifetime = time()+60 * 60;
        }
        return $lifetime;
    }

    /**
     * 获取session
     *
     * @param $key
     * @return mixed
     */
    public function get($key)
    {
        $key = $this->preKey.$key;
        $sid = $this->getSid();
        $lifetime = $this->getLifeTime();
        $sessionData = Home::dao()->getSessions()->get(['id'=>$sid]);
        if(!$sessionData) return null;
        $lifetimeTmp = $sessionData['lifetime'];
        if($lifetimeTmp<time()){
            $this->clear();
            return null;
        }else{
            $sessionValue = unserialize($sessionData['data']);
            if(isset($sessionValue[$key])){
                $result = $sessionValue[$key];
                $data = [];
                $data['modified'] = time();
                $data['lifetime'] = $lifetime;
                Home::dao()->getSessions()->update($data, ['id'=>$sid]);
                return $result;
            }
            return null;
        }
    }

    /**
     * 设置session
     * @param $key
     * @param $value
     */
    public function set($key, $value)
    {
        $key = $this->preKey.$key;
        $sid = $this->getSid();
        $lifetime = $this->getLifeTime();

        $sessionData = Home::dao()->getSessions()->get(['id'=>$sid]);
        if($sessionData){
            $sessionValue = unserialize($sessionData['data']);
            $data = [];
            $data['modified'] = time();
            $data['lifetime'] = $lifetime;
            if($value ===null){
                unset($sessionValue[$key]);
            }else{
                $sessionValue[$key] = $value;
            }
            $data['data'] = serialize($sessionValue);
            Home::dao()->getSessions()->update($data, ['id'=>$sid]);
        }else{
            if($value ===null) return ;
            $data = [];
            $data['id'] = $sid;
            $data['modified'] = time();
            $data['lifetime'] = $lifetime;
            $data['data'] = serialize([$key=>$value]);
            Home::dao()->getSessions()->insert($data);
        }
        return true;
    }

    /**
     * 获取id
     * @return null
     */
    public function getSid()
    {
        if(self::$sid) return self::$sid;
        $config = $this->config;
        $sessionName = empty($config['name']) ? 'YSESSIONID' : $config['name'];
        if (isset($_REQUEST[$sessionName]) && $_REQUEST[$sessionName]) {
            $sid = $_REQUEST[$sessionName];
        } elseif (isset($_COOKIE[$sessionName]) && $_COOKIE[$sessionName]) {
            $sid = $_COOKIE[$sessionName];
        } else {
            $sid = sha1(uniqid(posix_getpid(), true).time());
        }
        self::$sid = $sid;
        return $sid;
    }

    /**
     *  删除key
     * @param $key
     * @return mixed
     */
    public function del($key)
    {
        $key = $this->preKey.$key;
        $this->set($key, null);
        return true;
    }

    /**
     * 清空
     * @return mixed
     */
    public function clear()
    {
        $sid = $this->getSid();
        $where = [];
        $where['id'] = $sid;
        Home::dao()->getSessions()->del($where);
        return true;
    }
}